﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using System.IO;

/// <summary>
///usPatentGrabber 的摘要说明
/// </summary>
public class usPatentGrabber : Task
{
    private string pn = "";
    private string surl = "http://patimg1.uspto.gov/.piw?idkey=NONE&Docid=";
    private string imgurl = "http://patimg1.uspto.gov/.DImg?Docid={0}&PageNum={1}&IDKey={2}&ImgFormat=tif";

    public usPatentGrabber(string pn = "US6800782")
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
        this.pn = pn;
    }

    public override void SearchbyPN(Object stateInfo)
    {
        string pnpath = AppDomain.CurrentDomain.BaseDirectory + "PatentFiles\\" + pn + "\\";
        string prog = "";

        if (File.Exists(pnpath + pn + ".pdf"))
        {
            this.FireProgressChangedEvent(pn, "完成进度：100%");
            return;
        }
        if (!Directory.Exists(pnpath))
        {
            Directory.CreateDirectory(pnpath);
        }

        try
        {
            string npn = pn.ToUpper().Replace("US", "");
            string html = UtilsList.GetHtmlPage(surl + npn);
            Match m = Regex.Match(html, "<!-- NumPages=(\\d+) -->");
            int pagenum = Int32.Parse(m.Groups[1].Value);
            m = Regex.Match(html, "&IDKey=(\\w+)");
            string idkey = m.Groups[1].Value;

            //删除最后一个文件，以防下载不完整
            UtilsList.DeleteLatestFile(pnpath);

            for (int i = 0; i < pagenum; i++)
            {
                string durl = string.Format(imgurl, npn, i, idkey);

                
                if (File.Exists(pnpath + pn + i + ".tif"))
                {
                    continue;
                    /*if (UtilsList.GetLocalFileLength(pnpath + pn + i + ".tif")
                        <UtilsList.GetRemoteFileLength(durl))
                        continue;
                    else
                    {
                        File.Delete(pnpath + pn + i + ".tif");
                        UtilsList.DownloadFile(pnpath + pn + i + ".tif", durl);
                    }*/
                }
                else
                {
                    UtilsList.DownloadFile(pnpath + pn + i + ".tif", durl);
                }
                this.FireProgressChangedEvent(pn, 
                    "下载进度：" + ((i + 1.0) / pagenum*100).ToString("F1")+"%"
                    );
            }
            if (!File.Exists(pnpath + pn + ".pdf"))
            {
                PDFGenetor.ImgtoPdf(pnpath + pn + ".pdf", pnpath);
            }
            prog = "完成进度：100%";
        }
        catch (Exception ex)
        {
            prog = ex.Message; //throw ex;
        }
        this.FireProgressChangedEvent(pn, prog);
        return;
    }
}